﻿using HuaweiCloud.Dotnet.Samples.Common.Cache.Extension;
using HuaweiCloud.Dotnet.Samples.ESports.Common.Messages;
using HuaweiCloud.Dotnet.Samples.ESports.Main.Entities;
using HuaweiCloud.Dotnet.Samples.ESports.Main.Manager;
using HuaweiCloud.Dotnet.Samples.ESports.Main.Service;
using MassTransit;
using Microsoft.Extensions.Caching.Distributed;
using Newtonsoft.Json;

namespace HuaweiCloud.Dotnet.Samples.ESports.Main.Consumers
{

    public class PointsInfoConsumer : IConsumer<UpdateStepInfo>
    {
        private readonly IDeviceManager _deviceManager;
        private readonly IEventsManager _eventsManager;
        private readonly IPointsService _pointsService;
        public PointsInfoConsumer(IDeviceManager deviceManager
            , IEventsManager eventsManager
            , IPointsService pointsService)
        {
            _deviceManager = deviceManager;
            _eventsManager = eventsManager;
            _pointsService = pointsService;
        }
        public async Task Consume(ConsumeContext<UpdateStepInfo> context)
        {
            var msg = context.Message;
            if (msg == null || msg.DeviceId == null) 
                return;
            var userId = await _deviceManager.GetUserIdByDeviceIdAsync(Guid.Parse(msg.DeviceId));
            if (userId == null)
                return;
            // TODO: 比较任务集合确定是否获得积分
            var events = await _eventsManager.GetRunningAsync();
            if(events != null && events.Count > 0)
            {
                foreach(var e in events)
                {
                    if (await _eventsManager.CheckEventsCompletedAsync(userId.Value, e.Id))
                        continue;
                    var isCompleted = _eventsManager.CheckStepEvents(e, msg.Count);
                    if (isCompleted)
                    {
                        await _eventsManager.CompletedEventsAsync(userId.Value, e.Id);
                        await _pointsService.AddScoresAsync(userId.Value, e.Points);
                    }
                }
            }

        }
    }
}
